<!--平台管理-->
<script setup lang="ts">
import {AxiosPromise} from "axios";

defineOptions({
  name: "WebHook",
  inheritAttrs: false,
});

import {
	getWebHookPage,
	getWebHookForm,
	saveWebHook,
	deleteWebHook,
	enableWebHook,
	disableWebHook
} from "@/api/webHook";

import { WebHookQuery, WebHookForm } from "@/api/webHook/types";

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<WebHookQuery>({
  pageNum: 1,
  pageSize: 20,
});

const webHookList = ref<[]>();

const dialog = reactive<DialogOption>({
  visible: false,
});

const formData = reactive<WebHookForm>({
		status: 1
});

const rules = reactive({
	hookType: [{ required: true, message: "推送平台不能为空", trigger: "change" }],
	webHookUrl: [{ required: true, message: "WebHook地址不能为空", trigger: "blur" }],
});

/**
 * 查询
 */
function handleQuery() {
  loading.value = true;
  getWebHookPage(queryParams)
    .then(({ data }) => {
      webHookList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开字典类型表单弹窗
 *
 * @param dicTypeId 字典类型ID
 */
function openDialog(dicTypeId?: number) {
  dialog.visible = true;
  if (dicTypeId) {
    dialog.title = "修改消息推送";
    getWebHookForm(dicTypeId).then(({ data }) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增消息推送";
  }
}

/**
 * 字典类型表单提交
 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
		saveWebHook(formData)
		  .then(() => {
			ElMessage.success("保存成功");
			closeDialog();
			handleQuery();
		  })
		  .finally(() => (loading.value = false));
	}
  });
}

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**
 * 重置表单
 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
}

/**
 * 删除字典类型
 */
function handleDelete(dictTypeId?: number) {
  const dictTypeIds = [dictTypeId || ids.value].join(",");
  if (!dictTypeIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteWebHook(dictTypeIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

const dictDataDialog = reactive<DialogOption>({
  visible: false,
});

/**
 * 修改用户状态
 */
function handleStatusChange(row: { [key: string]: any }) {
		// 参数传过来时status的值已经改变
		if (row.status === 1) {
			return enableWebHook(row.id);
		} else {
			return disableWebHook(row.id);
		}
		row.status = row.status === 1 ? 0 : 1;
}

onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="推送平台" prop="hookType">
					<dictionary v-model="queryParams.hookType" type-code="WebHook" clearable/>
        </el-form-item>
        <el-form-item label="WebHook地址" prop="webHookUrl">
					<el-input v-model="queryParams.webHookUrl" clearable  placeholder="WebHook地址"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <template #header>
        <el-button
          v-hasPerm="['sys:webHook:save']"
          type="success"
          @click="openDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
		  		v-hasPerm="['sys:webHook:delete']"
          ><i-ep-delete />删除</el-button
        >
      </template>
      <el-table
        size="small"
        :header-row-style="{color: 'dimgray'}"
        v-loading="loading"
        highlight-current-row
        :data="webHookList"
        border
        @selection-change="handleSelectionChange"
				:height="webHookList && webHookList.length > 0 ? 580 : 130"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="推送平台" prop="hookType" width="100"/>
        <el-table-column label="WEB_HOOK地址" prop="webHookUrl"/>
        <el-table-column label="状态" width="80">
					<template #default="scope">
						<el-switch
								v-model="scope.row.status"
								v-hasPerm="['sys:webHook:status']"
								:inactive-value="0"
								:active-value="1"
								@change="handleStatusChange(scope.row)"
						/>
					</template>
				</el-table-column>
        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['sys:webHook:save']"
              type="primary"
              link
              size="small"
              @click.stop="openDialog(scope.row.id)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              v-hasPerm="['sys:webHook:delete']"
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.id)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
	  :close-on-click-modal="false"
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="150px"
      >
				<el-form-item label="推送平台" prop="hookType">
					<dictionary v-model="formData.hookType" type-code="WebHook" clearable/>
				</el-form-item>
				<el-form-item label="WEB_HOOK地址" prop="webHookUrl">
					<el-input type="textarea" rows="5" v-model="formData.webHookUrl" placeholder="请输入WEB_HOOK地址" clearable/>
				</el-form-item>
				<el-form-item label="状态" prop="status">
					<el-radio-group v-model="formData.status">
						<el-radio :label="1">启用</el-radio>
						<el-radio :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
